package com.buaa.airticketbookingsystem.Controller;

import com.buaa.airticketbookingsystem.Entity.*;
import com.buaa.airticketbookingsystem.Service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
@CrossOrigin
@RestController
public class UserCenterController {

    @Autowired
    private UserService userService;

    @Autowired
    private FlightService flightService;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private FavouriteService favouriteService;

    @Autowired
    private PurchaseRecordService purchaseRecordService;

    @PostMapping("/userCenter")

    public Map<String, Object> userCenterMessage(@RequestBody Map<String, String> remap){
        String userEmail = remap.get("email");
        User u = userService.selectUserByEmail(userEmail);
        double money = u.getMoney();
        Map<String, Object> resMap = new HashMap<>();
        List<FavouriteRecord> frList = favouriteService.searchFavouriteRecordsByUser(userEmail);
        List<PurchaseRecord> prList = purchaseRecordService.getAllPurchaseRecordByUser(userEmail);
        List<Flight> flightColletions = new ArrayList<>();
        List<Ticket> purchaseTicketsColletions = new ArrayList<>();
        for(FavouriteRecord fr : frList){
            Flight f = flightService.selectFlightByID(fr.getF_id());
            flightColletions.add(f);
        }
        for(PurchaseRecord pr : prList){
            purchaseTicketsColletions.add(ticketService.getTicketById(pr.getT_id()));
        }

        long date = new Date().getTime() / 1000;
        if(u.getLast_refund() == 0 || u.getLast_refund() + 30 * 24 * 60 * 60 < date){
            userService.highCredit(userEmail);
            u.setCredit(1);
        }


        resMap.put("res", true);
        resMap.put("message", "成功返回个人信息");
        resMap.put("favorite_list", flightColletions);
        resMap.put("order_list", purchaseTicketsColletions);
        resMap.put("no_list", prList);
        resMap.put("money", money);
        resMap.put("credit", u.getCredit());
        return resMap;
    }
}
